package com.gukun.springboot.tdengine.service.backuprecover.entity;

import cn.hutool.core.date.DateUtil;
import com.gukun.springboot.tdengine.domain.backuprecover.BackupRecoverLogEntity;
import com.gukun.springboot.tdengine.domain.backuprecover.BackupRecoverTaskEntity;
import com.gukun.springboot.tdengine.service.backuprecover.BackupRecoverLogService;

import java.util.Date;

/**
 * 备份日志记录器
 * @author zhang
 */
public class LogRecorder {
    private final BackupRecoverLogEntity logEntity;
    private final BackupRecoverLogService logService;
    private final StringBuilder messageBuilder = new StringBuilder();

    public LogRecorder(BackupRecoverTaskEntity task, BackupRecoverLogService logService, String startTime) {
        this.logEntity = new BackupRecoverLogEntity();
        this.logEntity.setTaskId(task.getId());
        this.logEntity.setOperateType(task.getOperateType());
        this.logEntity.setOperateTarget(task.getOperateTarget());
        this.logEntity.setStatus(2);
        this.logEntity.setStartTime(startTime);
        this.logService = logService;
    }

    public void appendMessage(String msg) {
        messageBuilder.append(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS ")).append(msg).append("\n");
    }

    public void save() {
        logEntity.setMessage(messageBuilder.toString());
        logService.saveOrUpdate(logEntity);
    }

    public void saveFailed(){
        logEntity.setMessage(messageBuilder.toString());
        logEntity.setStatus(0);
        logService.saveOrUpdate(logEntity);
    }

    public void saveSuccess(){
        logEntity.setMessage(messageBuilder.toString());
        logEntity.setStatus(1);
        logService.saveOrUpdate(logEntity);
    }

    public void updateFilePath(String filePath){
        logEntity.setFilePath(filePath);
    }

    public void updateEndTime(String endTimeStr) {
        logEntity.setEndTime(endTimeStr);
    }

    public boolean isRunning(){
        return logEntity.getStatus() == 2;
    }
}
